// src/pages/Networks/Networks.tsx
import React, { useEffect, useState } from 'react';
import {
  Card,
  Table,
  Button,
  Space,
  Tag,
  Modal,
  Form,
  Input,
  Switch,
  message,
} from 'antd';
import type { TableColumnsType } from 'antd';
import {
  PlusOutlined,
  PlayCircleOutlined,
  StopOutlined,
  DeleteOutlined,
} from '@ant-design/icons';
import { apiClient } from '../../api/client';

interface Network {
  name: string;
  uuid: string;
  active: boolean;
  autostart: boolean;
  bridge_name?: string;
  forward_mode?: string;
}

const Networks: React.FC = () => {
  const [networks, setNetworks] = useState<Network[]>([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [form] = Form.useForm();

  useEffect(() => {
    fetchNetworks();
  }, []);

  const fetchNetworks = async () => {
    setLoading(true);
    try {
      const { data } = await apiClient.get('/networks');
      setNetworks(data);
    } catch (error) {
      message.error('获取网络列表失败');
    } finally {
      setLoading(false);
    }
  };

  const handleStart = async (name: string) => {
    try {
      await apiClient.post(`/networks/${name}/start`);
      message.success('网络已启动');
      fetchNetworks();
    } catch (error) {
      message.error('启动失败');
    }
  };

  const handleStop = async (name: string) => {
    try {
      await apiClient.post(`/networks/${name}/stop`);
      message.success('网络已停止');
      fetchNetworks();
    } catch (error) {
      message.error('停止失败');
    }
  };

  const handleDelete = (name: string) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除网络 "${name}" 吗？`,
      okText: '删除',
      okType: 'danger',
      cancelText: '取消',
      onOk: async () => {
        try {
          await apiClient.delete(`/networks/${name}`);
          message.success('网络已删除');
          fetchNetworks();
        } catch (error) {
          message.error('删除失败');
        }
      },
    });
  };

  const handleCreate = async (values: any) => {
    try {
      await apiClient.post('/networks', values);
      message.success('网络创建成功');
      setModalVisible(false);
      form.resetFields();
      fetchNetworks();
    } catch (error) {
      message.error('创建失败');
    }
  };

  const columns: TableColumnsType<Network> = [
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '状态',
      dataIndex: 'active',
      key: 'active',
      render: (active: boolean) => (
        <Tag color={active ? 'success' : 'default'}>
          {active ? '活动' : '未激活'}
        </Tag>
      ),
    },
    {
      title: '桥接名称',
      dataIndex: 'bridge_name',
      key: 'bridge_name',
      render: (name?: string) => name || '-',
    },
    {
      title: '转发模式',
      dataIndex: 'forward_mode',
      key: 'forward_mode',
      render: (mode?: string) => mode || '-',
    },
    {
      title: '自动启动',
      dataIndex: 'autostart',
      key: 'autostart',
      render: (autostart: boolean) => (autostart ? '是' : '否'),
    },
    {
      title: '操作',
      key: 'actions',
      render: (_, record) => (
        <Space>
          {!record.active ? (
            <Button
              type="link"
              icon={<PlayCircleOutlined />}
              onClick={() => handleStart(record.name)}
            >
              启动
            </Button>
          ) : (
            <Button
              type="link"
              icon={<StopOutlined />}
              onClick={() => handleStop(record.name)}
            >
              停止
            </Button>
          )}
          <Button
            type="link"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record.name)}
            disabled={record.active}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <Card
        title="网络管理"
        extra={
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => setModalVisible(true)}
          >
            创建网络
          </Button>
        }
      >
        <Table
          columns={columns}
          dataSource={networks}
          rowKey="uuid"
          loading={loading}
        />
      </Card>

      <Modal
        title="创建网络"
        open={modalVisible}
        onCancel={() => {
          setModalVisible(false);
          form.resetFields();
        }}
        onOk={() => form.submit()}
      >
        <Form form={form} layout="vertical" onFinish={handleCreate}>
          <Form.Item
            label="网络名称"
            name="name"
            rules={[{ required: true, message: '请输入网络名称' }]}
          >
            <Input placeholder="例如: default" />
          </Form.Item>

          <Form.Item label="桥接名称" name="bridge_name">
            <Input placeholder="例如: virbr0" />
          </Form.Item>

          <Form.Item label="转发模式" name="forward_mode">
            <Input placeholder="例如: nat" />
          </Form.Item>

          <Form.Item name="autostart" valuePropName="checked">
            <Switch checkedChildren="自动启动" unCheckedChildren="手动启动" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default Networks;

